﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace AMStudio.Common
{
    public partial class UserInterfaceTagForm : Form
    {
        protected ExceptionManager ExManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();

        private UserInterfaceItem UIItem;
        public UserInterfaceTagForm(UserInterfaceItem item, bool writeable, bool empty)
        {
            this.UIItem = item;
            InitializeComponent();
            this.txtDevice.Items.Clear();

            for (int i = 0; i < MachineConfig.Default.Devices.Length; i++)
            {
                //DeviceName d = MachineConfig.Default.Devices[i];
                this.txtDevice.Items.Add(MachineConfig.Default.Devices[i]);
            }
            this.RefreshUI(writeable, empty);
        }
        private void RefreshUI(bool writeable, bool empty)
        {
            if (this.UIItem.RelatedControl != null)
            {
                this.ribbonControl1.TitleText = "   " + this.UIItem.RelatedControl.Text + " Tag Information";
                this.ribbonControl1.Text = "   " + this.UIItem.RelatedControl.Text + " Tag Information";
            }
            this.txtAction.Text = this.UIItem.Action;
            this.txtDevice.Text = this.UIItem.Device;
            this.txtDisplayTag.Text = this.UIItem.DisplayTag;
            this.txtRefreshGroup.Text = this.UIItem.DisplayRefreshGroup;
            this.txtRemark.Text = this.UIItem.Remark;

            if (writeable)
            {
                if (empty)
                {
                    this.radioButtonEnabled.Checked = false;
                    this.radioButtonDisabled.Checked = true;
                }
                else
                {
                    this.radioButtonEnabled.Checked = true;
                    this.radioButtonDisabled.Checked = false;
                }
                this.groupPanelInformation.Enabled = !this.radioButtonDisabled.Checked;
                this.txtAction.ReadOnly = false;
                this.txtDevice.Enabled = true;
                this.txtDisplayTag.ReadOnly = false;
                this.txtRefreshGroup.ReadOnly = false;
                this.txtRemark.ReadOnly = false;
            }
            else
            {
                this.radioButtonDisabled.Enabled = false;
                this.radioButtonEnabled.Enabled = false;
                this.txtAction.ReadOnly = true;
                this.txtDevice.Enabled = false;
                this.txtDisplayTag.ReadOnly = true;
                this.txtRefreshGroup.ReadOnly = true;
                this.txtRemark.ReadOnly = true;
            }
        }

        private void radioButtonDisabled_CheckedChanged(object sender, EventArgs e)
        {
            this.groupPanelInformation.Enabled = !this.radioButtonDisabled.Checked;
        }
        private Regex AddressRegex = new Regex(
            @"^\s*(NOT )?(?<RegType>(CIO|[ATHCWED]))(?<StartAddress>\d{1,5})(.(?<BitIndex>([0-1][0-9]|1[0-5]|\d{1})))?\s*$");

        private bool ValidateAddress()
        {
            try
            {
                if (!string.IsNullOrEmpty(this.txtDisplayTag.Text.Trim()))
                {
                    string[] displays = this.txtDisplayTag.Text.Trim().Split(';');
                    foreach (string display in displays)
                    {
                        if (!AddressRegex.IsMatch(display))
                        {
                            return false;
                        }
                    }
                }
                if (!string.IsNullOrEmpty(this.txtAction.Text.Trim()))
                {
                    string[] actions = this.txtAction.Text.Trim().Split(';');
                    foreach (string action in actions)
                    {
                        string[] actionTags = action.Split('=');
                        if (actionTags.Length > 1)
                        {
                            if (!AddressRegex.IsMatch(actionTags[0]))
                            {
                                return false;
                            }
                        }
                        else if (AddressRegex.IsMatch(actionTags[0]))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExManager.HandleException(ex, "Policy");
                return false;
            }
            return true;
        }
        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (this.radioButtonDisabled.Checked)
            {
                this.DialogResult = DialogResult.Ignore;
            }
            else
            {
                if ((this.txtDevice.Text.Trim() == "DialTable PLC") || (this.txtDevice.Text.Trim() == "Oven PLC"))
                {
                    if (!ValidateAddress())
                    {
                        System.Windows.Forms.MessageBox.Show("Wrong Display Tag Address or Action Address");
                        return;
                    }
                }
                else
                {
                }
                //else
                //{
                //    MessageBox.Show("Please select the device first");
                //    return;
                //}
                //if (UIItem == null)
                //    this.UIItem = new UserInterfaceItem();
                this.UIItem.Action = this.txtAction.Text.Trim();
                this.UIItem.Device = this.txtDevice.Text.Trim();
                this.UIItem.DisplayTag = this.txtDisplayTag.Text.Trim();
                this.UIItem.DisplayRefreshGroup = this.txtRefreshGroup.Text.Trim();
                this.UIItem.Remark = this.txtRemark.Text.Trim();
                this.DialogResult = DialogResult.OK;
            }

            this.Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {

        }

        private void UserInterfaceTagForm_Load(object sender, EventArgs e)
        {

        }
    }
}
